package com.example.server.utils;

import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.util.*;
import java.util.stream.Collectors;


public class DataRelationUtils {
    private static Logger logger = LoggerFactory.getLogger(DataRelationUtils.class);

    /**
     * @Description 设置主从关系
     * @Param parentData:父,childrenData:子,key:设置属性key,parentKey:父KEY,childrenKey:子KEY
     * @return
     **/
    public static <T> void setRelationByField(Collection<? extends T> parentData,Collection<? extends T> childrenData, String key, String parentKey, String childrenKey) throws Exception{
       try {
           T t;
           Iterator it = parentData.iterator();
           while (it.hasNext()){
                t = (T) it.next();
               if (t instanceof Map){
                   Map pMap = (Map) t;
                   setRelation(pMap,childrenData,key,parentKey,childrenKey);
               }else{
                   setRelationClazz(t,childrenData,key,parentKey,childrenKey);
               }
           }
       }catch (Exception e){
           logger.error("数据重组失败",e.getMessage(),e);
           throw new Exception("数据重组失败"+ e.getMessage());
       }


    }
    public static Map setRelation(Map parentData, Collection<?> childrenData, String key, String parentKey,String childrenKey){
        //过滤数据
        List children = childrenData.stream().filter(map ->MapUtils.getString(parentData,parentKey).equals(MapUtils.getString((Map) map,childrenKey))).collect(Collectors.toList());
        parentData.put(key,children);
        return parentData;
    }


    public static <T> T setRelationClazz(T parentData, Collection<? extends T> childrenData, String key, String parentKey,String childrenKey) throws NoSuchFieldException, IllegalAccessException, InstantiationException {
        Field field = parentData.getClass().getDeclaredField(key);
        field.setAccessible(true);
        Field parent = parentData.getClass().getDeclaredField(parentKey);
        parent.setAccessible(true);
        String pv = (String) parent.get(parentData);
        List childrenList = new ArrayList();
        for (T t : childrenData){
            Field subField = t.getClass().getDeclaredField(childrenKey);
            subField.setAccessible(true);
            String v = (String) subField.get(t);
            if (v.equals(pv)){
                childrenList.add(t);
            }
        }
        field.set(parentData,childrenList);
        return parentData;
    }
}
